package com.atguigu.daijia.dispatch.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.dispatch.mapper.OrderJobMapper;
import com.atguigu.daijia.dispatch.service.NewOrderService;
import com.atguigu.daijia.dispatch.xxl.client.XxlJobClient;
import com.atguigu.daijia.model.entity.dispatch.OrderJob;
import com.atguigu.daijia.model.vo.dispatch.NewOrderTaskVo;
import com.atguigu.daijia.model.vo.order.NewOrderDataVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class NewOrderServiceImpl implements NewOrderService {

    @Resource
    private XxlJobClient xxlJobClient;

    @Resource
    private OrderJobMapper orderJobMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Long addAndStartTask(NewOrderTaskVo newOrderTaskVo) {
        // 1. 先判断订单是否已经存在该任务。
        Long orderId = newOrderTaskVo.getOrderId();

        OrderJob orderJob = orderJobMapper.selectOne(new QueryWrapper<OrderJob>().eq("order_id", orderId));
        if (!ObjectUtils.isEmpty(orderJob)) {
            return null;
        }
        // 2. 不存在任务，就新建xxljob任务，并自动启动任务
        // 该任务，每分钟执行一次
        Long jobId = xxlJobClient.addAndStart("searchNearbyDrivers", "", "0 0/1 * * * ?", "每分钟查找附近5公里内的司机");
        // 3. 得到任务id，将任务信息存入数据库
        orderJob = new OrderJob();
        orderJob.setOrderId(orderId);
        orderJob.setJobId(jobId);
        orderJob.setParameter(JSONObject.toJSONString(newOrderTaskVo));
        orderJobMapper.insert(orderJob);
        return jobId;
    }

    // 获取最新订单
    @Override
    public List<NewOrderDataVo> findNewOrderQueueData(Long driverId) {
        String redisKey = RedisConstant.DRIVER_ORDER_TEMP_LIST + driverId;
        Long size = redisTemplate.opsForList().size(redisKey);
        ArrayList<NewOrderDataVo> newOrderDataVoArrayList = new ArrayList<>();
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                String jsonStr = (String) redisTemplate.opsForList().leftPop(redisKey);
                NewOrderDataVo newOrderDataVo = JSONObject.toJavaObject((JSON) JSONObject.parse(jsonStr), NewOrderDataVo.class);
                newOrderDataVoArrayList.add(newOrderDataVo);
            }
        }
        return newOrderDataVoArrayList;
    }


    // 清空队列数据
    @Override
    public Boolean clearNewOrderQueueData(Long driverId) {
        String key = RedisConstant.DRIVER_ORDER_TEMP_LIST + driverId;
        redisTemplate.delete(key);
        return true;
    }
}
